package tree;

/**
 * @ClassName BalanceTreeNode
 * @Description TODO
 * @Author lenovo
 * @Date 2023-03-10 9:25
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class BalanceTreeNode {
    /**
     * 110. 平衡二叉树
     * 给定一个二叉树，判断它是否是高度平衡的二叉树。
     * <p>
     * 本题中，一棵高度平衡二叉树定义为：
     * <p>
     * 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
     */


    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        int isBalance = judgeIsBalance(root);
        return isBalance != -1 ? true : false;
    }

    private int judgeIsBalance(TreeNode root) {
        if (root == null) return 0;
        int left = judgeIsBalance(root.left);
        int right = judgeIsBalance(root.right);
        if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
            return -1;
        }
        return Math.max(left, right) + 1;
    }

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(2);

        TreeNode treeNodeLeft = new TreeNode(1);
        treeNode.left = treeNodeLeft;
//
        TreeNode treeNodeRight = new TreeNode(3);
        treeNode.right = treeNodeRight;

        BalanceTreeNode balanceTreeNode = new BalanceTreeNode();
        System.out.println(balanceTreeNode.isBalanced(treeNode));

    }
}